﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DeepZoomPivotConstructor.PivotLib;
using DeepZoomPivotConstructor.ErrorAndLoggingInterfaces;

namespace PivotPhysicsPlotsGenerator
{
    public static class MarkExceptions
    {
        /// <summary>
        /// When an error appears, wrap it so that up-level can figure out what happened when it is written out.
        /// </summary>
        /// <param name="source"></param>
        /// <param name="extraInfo"></param>
        /// <returns></returns>
        public static IEnumerable<PivotImage> TrackErrors(this IEnumerable<PivotImage> source, string extraInfo)
        {
            bool done = false;
            var iter = source.GetEnumerator();
            PivotImage img = null;
            while (!done)
            {
                try
                {
                    done = !iter.MoveNext();
                    if (!done)
                    {
                        img = iter.Current;
                    }
                }
                catch (Exception e)
                {
                    Exception newe = new Exception(extraInfo, e);
                    throw newe;
                }
                if (!done)
                {
                    yield return img;
                }
            }
        }

        /// <summary>
        /// Runs an action right before the first time.
        /// </summary>
        /// <param name="source"></param>
        /// <param name="what"></param>
        /// <returns></returns>
        public static IEnumerable<PivotImage> RunThisAtStart(this IEnumerable<PivotImage> source, Action what)
        {
            what();
            foreach (var item in source)
            {
                yield return item;
            }
        }
    }
}
